import calendar
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from datetime import datetime
from fdafeed.models import Company, Recall


def home(request):
    
    response_dict = {}
    
    # Aggregates
    today = datetime.today()
    recalls_this_month = Recall.objects.filter(when__month=today.month, when__year=today.year)
    recalls_this_year = Recall.objects.filter(when__year=today.year).count()
    response_dict.update({ 'recalls_this_month':len(recalls_this_month), 'recalls_this_year':recalls_this_year })
    
    # Most recent recalls
    recalls = Recall.objects.all().order_by('-when')[0:30]
    
    # Recalls by day
    monthrange = calendar.monthrange(today.year, today.month)
    recalls_by_day = []
    for i in range(monthrange[1]):
        recalls_by_day.append(0)
    
    for r in recalls_this_month:
        recalls_by_day[r.when.day-1] += 1
    recalls_max = max(recalls_by_day)
    response_dict.update({ 'recalls_by_day':recalls_by_day, 'recalls_max':recalls_max })
    
    # Number of recalls by month
    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute("SELECT YEAR(`when`), MONTH(`when`), COUNT(*) FROM `fdafeed_recall` GROUP BY YEAR(`when`), MONTH(`when`) ORDER BY YEAR(`when`) DESC, MONTH(`when`) DESC")
    recalls_by_month = list(cursor.fetchall()[0:12])  
    recalls_by_month.reverse()
    
    response_dict.update({ 'recalls': recalls, 'recalls_by_month':recalls_by_month })
    
    companies = Company.objects.annotate(num_recalls=Count('recall')).order_by('-num_recalls')[0:15]
    response_dict.update({ 'companies':companies })
    
    reasons = Recall.objects.values('reason').annotate(Count('reason')).order_by('-reason__count')[0:10]
    response_dict.update({ 'reasons': reasons })
    
    return render_to_response('recallviewer/home.html', response_dict, context_instance=RequestContext(request))


def company_view(request, company_id):
    
    response_dict = {}
    
    try:
        company = Company.objects.get(pk=company_id)
    except:
        return HttpResponse("No records for this company.")
    
    response_dict.update({ 'title': company.name })
    
    # Aggregates
    today = datetime.today()
    recalls_count = Recall.objects.filter(company=company).count()
    response_dict.update({ 'recalls_count':recalls_count, 'today':today })
    
    # Recalls by day
    monthrange = calendar.monthrange(today.year, today.month)
    recalls_by_day = []
    for i in range(monthrange[1]):
        recalls_by_day.append(0)
    
    recalls_month = Recall.objects.filter(when__year=today.year, when__month=today.month, company=company)
    for r in recalls_month:
        recalls_by_day[r.when.day-1] += 1
    recalls_max = max(recalls_by_day)
    response_dict.update({ 'recalls_by_day':recalls_by_day, 'recalls_max':recalls_max })
    
    # Most recent recalls
    recalls = Recall.objects.filter(company=company).order_by('-when')
    response_dict.update({ 'recalls':recalls })
    
    # Most common reasons
    reasons = Recall.objects.filter(company=company).values('reason').annotate(Count('reason')).order_by('-reason__count')
    response_dict.update({ 'reasons': reasons })
    
    return render_to_response('recallviewer/company.html', response_dict, context_instance=RequestContext(request))


def month_view(request, year, month):
    
    response_dict = { 'title': 'Recalls during ' + calendar.month_name[int(month)] + ' ' + year }
    
    this_month_dt = datetime(int(year), int(month), 1)
    response_dict.update({ 'this_month_dt':this_month_dt })
    
    recalls = Recall.objects.filter(when__year=year, when__month=month).order_by('-when')
    response_dict.update({ 'recalls':recalls, 'recalls_count':len(recalls) })
    
    # Recalls by day
    monthrange = calendar.monthrange(int(year), int(month))
    recalls_by_day = []
    for i in range(monthrange[1]):
        recalls_by_day.append(0)
    
    for r in recalls:
        recalls_by_day[r.when.day-1] += 1
    recalls_max = max(recalls_by_day)
    response_dict.update({ 'recalls_by_day':recalls_by_day, 'recalls_max':recalls_max })
    
    # Most common reasons
    reasons = Recall.objects.filter(when__year=year, when__month=month).values('reason').annotate(Count('reason')).order_by('-reason__count')
    response_dict.update({ 'reasons': reasons })
    
    return render_to_response('recallviewer/generic_list.html', response_dict, context_instance=RequestContext(request))
    
    
def recall_view(request, recall_id):
    
    response_dict = {}
    
    recalls = Recall.objects.filter(pk=recall_id)
    response_dict.update({'recalls':recalls})
    
    return render_to_response('recallviewer/recall_view.html', response_dict, context_instance=RequestContext(request))
    
    
    
    